#pragma once

#include <iostream>
#include "epoller.hpp"
#include "util.hpp"

namespace ns_appinterface{

    using namespace ns_epoll;

    int recver(EventItem *item);
    int sender(EventItem *item);
    int errorer(EventItem *item);

    //请问，什么时候会调用这里的accepter?
    int accepter(EventItem *item)
    {
        std::cout << "get a new link: " << item->sock << std::endl;
        while(true){
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(item->sock, (struct sockaddr*)&peer, &len);
            if(sock < 0){
                if(errno == EAGAIN || errno == EWOULDBLOCK){
                    //说明并没有读取出错，只是底层没有链接了!
                    return 0;
                }
                if(errno == EINTR){
                    //读取的过程被信号打断了
                    continue;
                }
                else{
                    //真正的出错了
                    return -1;
                }
            }
            else{
                ns_util::SetNonBlock(sock);
                //读取成功了!
                EventItem tmp;
                tmp.sock = sock;
                tmp.R = item->R;
                tmp.ManagerCallBack(recver, sender, errorer);
                Epoller *epoller = item->R;
                epoller->AddEvent(sock, EPOLLIN|EPOLLET, tmp);

            }
        }
        return 0;
    }

    int recver(EventItem *item)
    {
        //负责数据读取
        return 0;
    }

    int sender(EventItem *item)
    {
        return 0;
    }
    int errorer(EventItem *item)
    {
        return 0;
    }
}
